﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Xml.Serialization;
using Kristall.Engine;

namespace Kristall.MyGame.Enemies
{
    public class CrystalDrainerEnemy : Enemy
    {
        AnimatableSprite idle;

        public float Range { get; set; }

        private float _rotation { get; set; }

        [XmlIgnore]
        public float Rotation
        {
            get
            {
                return _rotation;
            }
            set
            {
                _rotation = MathHelper.ToRadians(value);

                if (CurrentAnimation != null)
                    CurrentAnimation.Rotation = _rotation;
            }
        }

        private float cooldownTimer = 0;

        public float RateOfFire
        {
            get;
            set;
        }

        public CrystalDrainerEnemy()
        {
            Range = 500;
            GravityAcceleration = 0;
            _rotation = 0;
            RateOfFire = 5f;
        }

        public override void LoadContent(Level level)
        {
            idle = new AnimatableSprite("Enemies/Drainer/Drainer.xnb");
            idle.FrameHeight = 29;
            idle.Rotation = Rotation;
            Animations.Clear();
            Animations.Add(idle);
            this.CurrentAnimationKey = "Enemies/Drainer/Drainer.xnb";
            
            base.LoadContent(level);
            idle.FrameCount = 1;

            idle.Origin = new Vector2(idle.FrameWidth, idle.FrameHeight) * 0.5f;
            idle.Offset = idle.Origin;

            this.Height = idle.FrameHeight;
            this.Width = idle.FrameWidth;

            cooldownTimer = RateOfFire;

            Health = 2;
        }

        private void Fire()
        {
            cooldownTimer = 0;

            //Spawn a Flying enemy
            FlyingEnemy fe = new FlyingEnemy();
            fe.LoadContent(Level);
            fe.Position = this.Position - Vector2.UnitY * idle.FrameHeight * 0.5f;
            Random r = new Random();

            float random = (float)(r.NextDouble()) * 2f - 1f;
            float rotation = Rotation + random * MathHelper.ToRadians(30);
            fe.Velocity = new Vector2((float)-Math.Sin(rotation), -(float)Math.Cos(rotation)) * 800f;
            
            fe.AddToLevel();            
        }

        public override void Update(float dt)
        {
            if (!IsAlive)
            {
                this.RemoveFromLevel();
                return;
            }

            cooldownTimer += dt;

            float distanceToPlayer = Vector2.Distance(this.Level.Player.Position, this.Position);

            if (distanceToPlayer < Range && (cooldownTimer >= RateOfFire))
                Fire();


            
            base.Update(dt);
        }




    }
}
